﻿'
' Boogaloo® - http://www.mindfly.com
' Copyright (c) 2008-2009
' by Mindfly, Inc.
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
' INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
' DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
' SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
' SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
' WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
' THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Imports System
Imports System.IO
Imports System.Web
Imports System.Net
Imports System.Xml
Imports System.Text
Imports System.IO.Compression
Imports System.Text.RegularExpressions

Imports Boogaloo.Base
Imports Boogaloo.Core
Imports Boogaloo.Core.UI
Imports Boogaloo.Core.BLL
Imports Boogaloo.Syndication.XmlRpc

Namespace HttpHandlers

    ''' <summary>
    ''' Recieves pingbacks from other blogs and websites, and 
    ''' registers comments.
    ''' </summary>
    ''' <remarks>Adaptation of BlogEngine.NET's PingbackHandler</remarks>
    Public Class PingbackHandler
        Implements IHttpHandler

#Region "HttpHandler"

#Region "Private fields"

        Private Shared ReadOnly _regex As Regex = New Regex("(?<=<title.*>)([\s\S]*)(?=</title>)", RegexOptions.IgnoreCase Or RegexOptions.Compiled)
        Private Shared ReadOnly REGEX_HTML As Regex = New Regex("</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline Or RegexOptions.Compiled)
        Private Const SUCCESS As String = "<methodResponse><params><param><value><string>Thanks!</string></value></param></params></methodResponse>"

        Private _title As String
        Private _source_has_link As Boolean
        Private _contains_html As Boolean

#End Region


        Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest



            If Not CoreSettings.APIs("pingback").expose Then
                context.Response.StatusCode = 404
                context.Response.End()
            End If
            EventLogger.Write("Recieved a pingback", "PingbackHandler")

            Dim req As New XmlRpcRequest(context)
            If Not String.Equals(req.methodName, "pingback.ping") Then
                context.Response.StatusCode = 404
                context.Response.End()
            End If

            EventLogger.Write("Parsed the pingback", "PingbackHandler")

            Dim source_uri As Uri = Nothing
            Dim target_uri As Uri = Nothing

            Try
                source_uri = New Uri(req.params(0).Value)
                target_uri = New Uri(req.params(1).Value)
            Catch ex As Exception

            End Try

            'EventLogger.Write(String.Format("Source: {0} | Target: {1}", source_uri.ToString, target_uri.ToString), "PingbackHandler")

            ExamineSourcePage(source_uri, target_uri.ToString)

            context.Response.ContentType = "text/xml"

            Dim n As Node = GetNodeByUri(target_uri)
            If n IsNot Nothing Then

                If IsFirstPingBack(n, source_uri) Then

                    If _source_has_link And Not _contains_html Then

                        AddComment(source_uri, n)

                        Dim value As New XmlRpcValue("Thanks!", XmlRpcValue.ValueType.str)
                        context.Response.Write(XmlRpcResponse.ToXmlString(value))
                    ElseIf Not _source_has_link Then

                        SendError(context, 17, "The source URI does not contain a link to the target URI, and so cannot be used as a source.")

                    Else

                        ' Don't let spammers know we exist
                        context.Response.StatusCode = 404

                    End If


                Else
                    SendError(context, 48, "The pingback has already been registered.")
                End If


            Else
                SendError(context, 32, "The specified target URI does not exist.")
            End If

        
        End Sub

        ''' <summary>
        ''' Parse the HTML of the source page and look at the title
        ''' </summary>
        Private Sub ExamineSourcePage(ByVal source_uri As Uri, ByVal target_uri As String)

            Try
                Dim html As String = Groove.DownloadWebPage(source_uri)
                _title = _regex.Match(html).Value.Trim
                _contains_html = REGEX_HTML.IsMatch(_title)
                _source_has_link = html.ToUpperInvariant().Contains(target_uri.ToString.ToUpperInvariant)

            Catch wex As WebException
                _source_has_link = False
            End Try

        End Sub

        ''' <summary>
        ''' Checks to see if the source has already pinged the target.
        ''' </summary>
        Private Function IsFirstPingBack(ByVal n As Node, ByVal source_url As Uri)

            Dim c As Comment = Nothing
            For Each c In n.comments

                If String.Equals(c.website, source_url.ToString, StringComparison.OrdinalIgnoreCase) Then Return False
                If String.Equals(c.ip, HttpContext.Current.Request.UserHostAddress) Then Return False

            Next

            Return True
        End Function

        ''' <summary>
        ''' Response with an xml rpc error
        ''' </summary>
        Private Sub SendError(ByVal context As HttpContext, ByVal faultCode As Integer, ByVal message As String)
            Dim fault As New XmlRpcFault
            fault.faultCode = faultCode
            fault.message = message

            EventLogger.Write(XmlRpcResponse.ToXmlString(fault), "PingbackHandler", True)

            context.Response.Write(XmlRpcResponse.ToXmlString(fault))
        End Sub

        Private Sub AddComment(ByVal source_url As Uri, ByVal n As Node)
            Dim author As String = source_url.Host.Replace("www.", String.Empty)
            Dim body As String = String.Format("Pingback from {0}{1}{1}{2}", author, Environment.NewLine, Environment.NewLine, _title)
            Dim comment_id As Integer = Comment.InsertComment(n.entity_key, source_url.Host.Replace("www.", String.Empty), "pingback", source_url.ToString, DateTime.Now, body, True, False)
        End Sub

        ''' <summary>
        ''' Finds the target node and returns it
        ''' </summary>
        Private Function GetNodeByUri(ByVal url As Uri) As Node
            Return Node.GetNodeByVirtualPathRewritten(Groove.site_root.root_id, url.LocalPath)
        End Function

        Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
            Get
                Return True
            End Get
        End Property

#End Region

    End Class


End Namespace